package com.weiss.jpro.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weiss.jpro.dto.Result;
import com.weiss.jpro.entity.ShopType;
import com.weiss.jpro.mapper.ShopTypeMapper;
import com.weiss.jpro.service.IShopTypeService;
import com.weiss.jpro.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        // 1.判断redis是否命中
        String cacheTypeKey = RedisConstants.CACHE_TYPE_KEY;
        // 获取店铺列表长度
        Long shopSize = stringRedisTemplate.opsForList().size(cacheTypeKey);
        // 判断店铺列表是否为空
        if (shopSize != null&&shopSize != 0) {
            // 非空，获取店铺信息Json列表
            List<String> shopJsonList = stringRedisTemplate.opsForList().range(cacheTypeKey, 0, shopSize - 1);
            // 新建店铺类型列表存储店铺信息
            List<ShopType> shopTypeList = new ArrayList<>();
            for (String shopJson : shopJsonList){
                // hutool工具类反序列化JSON
                ShopType shop = JSONUtil.toBean(shopJson, ShopType.class);
                // 添加店铺信息
                shopTypeList.add(shop);
            }
            log.debug("redis命中");
            return Result.ok(shopTypeList);
        }

        // 2.未命中，从数据库查询
        List<ShopType> shopList = query().orderByAsc("sort").list();
        log.debug("redis未命中");
        if (shopList == null) {
            // 数据库不存在
            return Result.fail("数据库没有店铺类型信息");
        }

        // 3.存入redis，返回数据
        // hutool工具类序列化
        // 新建string列表存储序列化后店铺信息
        List<String> jsonShopList = new ArrayList<>();
        for (ShopType shopType : shopList){
            // 反序列化
            String shopJson = JSONUtil.toJsonStr(shopType);
            jsonShopList.add(shopJson);
        }
        // 存入redis
        stringRedisTemplate.opsForList().rightPushAll(cacheTypeKey, jsonShopList);
        return Result.ok(jsonShopList);
    }
}